package com.yj.idempotence.thread;

import java.util.LinkedList;

public class Demo06 {

    public static void main(String[] args) {
        Factory factory = new Factory();
        Produce produce = new Produce(factory);
        Consumer1 consumer = new Consumer1(factory);
        new Thread(produce,"生产者").start();
        new Thread(consumer,"消费者").start();
    }
}

class Factory{

    static int capacity = 10;
    LinkedList<String> linkedList;

    public Factory() {
        this.linkedList = new LinkedList<String>();
    }

    public void produce(String stockName) throws InterruptedException {
        while (linkedList.size() != capacity) { //如果没有达到库存10 上线就可以一直生产商品
            linkedList.add(stockName);
            System.out.println("生产商品："+stockName+"成功，当前剩余的商品："+linkedList.size());
            Thread.sleep(4000);
            //每有一件商品生产就通知消费者消费

        }
        System.out.println("当前库存已经达到了10最大库存值，请稍后生产");
        wait();
    }

    public void consumer() throws InterruptedException {
        while (linkedList.size()>0){
            //只要库存中有商品就可以一直消费
            linkedList.pop();
            System.out.println("线程("+Thread.currentThread().getName() + ")消费了一件产品:" + linkedList+";当前剩余商品"+linkedList.size()+"个");
            Thread.sleep(5000);
            notify();
        }
        System.out.println("警告：线程("+Thread.currentThread().getName() + ")准备消费产品，但当前没有产品");
        wait();
    }

}
class Produce implements Runnable{

    private Factory factory;
    int i = 1;
    public Produce(Factory factory){
        this.factory = factory;
    }


    @Override
    public void run() {
        try {
            while (true) {
                factory.produce(String.valueOf(i));
                i++;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Consumer1 implements Runnable{
    private Factory factory;
    int i = 0;
    public Consumer1(Factory factory){
        this.factory = factory;
    }


    @Override
    public void run() {
        try {
            while (true) {
                factory.consumer();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}